/**
 * @param #container        页面容器ID
 * @param #chartContainer   图表容器ID
 * @param #productList>a   产品列表ID-data[id][name]
 * @param #chart-tab>li     图表单位列表ID-data[unit]
 * @param #productPrice+id  产品价格ID前缀
 * @param #lineOption       分时线自定义参数ID
 * @param #kOption          K线自定义参数ID
 */
$(function() {
    var chart = echarts.init(document.getElementById('chartContainer')),
        pid = $("#productList>a.active").data('id'),
        productMap = {},
        rawData = {},
        data = {};
    var isTrade = $("#istrade").html();
    // 产品更换按钮
    $("body").on('click', '#productList>a', function() {
        // showChart();
    });
    // K线周期切换栏
    $("body").on('click', '#chart-tab>a', function(e) {
        e.preventDefault();
        var $this = $(this);
        if (!$this.hasClass('active')) {
            var $li = $(this),
                $a = $li.find('a');
            $this.addClass('active').siblings().removeClass('active');
            showChart();
        }
    });
    function transData(msg){
        var arr = [];
        for(var key in msg){
            var _arr = msg[key];
            _arr["time"] /= 1000;
        }
        arr.push(_arr);
        return msg;
    }
    // 获取数据
    var getRawData = function(callback) {
            $.get('/site/get-data', {
                name: $("#productList>a.active").data('name'),
                id: $("#productList>a.active").data('id'),
            }, function(msg) {
                msg = transData(msg);
                rawData[pid] = msg;
                callback();
                var row = [];
                data[pid][1441] = {
                    x: [],
                    y: []
                };
                for (var key in msg) {
                    row = [];
                    row[0] = msg[key].open;
                    row[1] = msg[key].close;
                    row[2] = msg[key].low;
                    row[3] = msg[key].high;
                    data[pid][1441].x.push(msg[key].time);
                    data[pid][1441].y.push(row);
                }
        }, 'json');
    }
    // 渲染指定条件的图表
    var showChart = function() {
        pid = $("#productList>a.active").data('id');
        if (!rawData[pid]) {
            rawData[pid] = {};
            data[pid] = {};
            getRawData(function() {
                getChart();
            });
        } else {
            getChart();
        }
    }
    var getChart = function() {
        var unit = $("#chart-tab>a.active").data('unit');
        if (unit == -1) {
            getAreaLine(unit);
        } else {
            getKLine(unit);
        }
    }

    // 数据整理
    var setData = function(unit) {
        if (rawData[pid].length > 0 && !data[pid][unit]) {
            data[pid][unit] = {
                x: [],
                y: []
            };
            var diff = 60 * (unit - 1),
                start = rawData[pid][0]['time'],
                end,
                row = [0, 0, 9999999, 0];
            for (var key in rawData[pid]) {
                end = rawData[pid][key]['time'];
                if (end == start) {
                    row[0] = rawData[pid][key]['open'];
                }
                if (row[2] > rawData[pid][key]['low']) {
                    row[2] = rawData[pid][key]['low'];
                }
                if (row[3] < rawData[pid][key]['high']) {
                    row[3] = rawData[pid][key]['high'];
                }
                row[1] = rawData[pid][key]['close'];
                if (rawData[pid][+key + 1]) {
                    if (rawData[pid][+key + 1]['time'] - start > diff) {
                        data[pid][unit].x.push(end);
                        data[pid][unit].y.push(row);
                        start = rawData[pid][+key + 1]['time'];
                        row = [0, 0, 9999999, 0];
                    }
                } else {
                    data[pid][unit].x.push(end);
                    data[pid][unit].y.push(row);
                }
            }
        }
    };
    // 分时线
    var getAreaLine = function(unit) {
        unit = unit || 1;
        setData(unit);
        var length = data[pid][unit].x.length;
        if (length > 60) {
            data[pid][unit].x = data[pid][unit].x.slice(length - 60);
            data[pid][unit].y = data[pid][unit].y.slice(length - 60);
        }
        var y = data[pid][unit].y.map(function(item) {
            return item[1];
        });


        if (length > 0) {
            var $pointLabel = $(".aniContainer");
        };
        var option = {
            tooltip: {
                trigger: 'axis',
                borderColor: 'black',
                formatter: function(params) {
                    var name = params[0].name,
                        value = params[0].value;
                    return '时间：' + new Date(Number(name) * 1000).format('hh:mm') + '<br />价格：' + value + '<br />'
                }
            },
            grid: {
                show: false,
                left: '1.5%',
                right: '1%',
                bottom: '0%',
                containLabel: true,
                borderWidth: 0,
                borderColor: 'white',
                y: 20,
                x2: 5,
                x: 45,
                y2: 40,
                borderWidth: 0
            },
            animation: true,
            xAxis: [{
                type: 'category',
                data: data[pid][unit].x,
                axisLabel: {
                    formatter: function(value, index) {
                        if (index == 0) {
                            prefix = '      ';
                        } else {
                            prefix = '';
                        }
                        return prefix + new Date(Number(value) * 1000).format('hh:mm');
                    },
                    interval: 10,
                },
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
            }],
            yAxis: [{
                type: 'value',
                scale: true,
                axisLabel: {
                    inside: true,
                    margin: 0,
                    formatter: function (value, index) {
                        return value + "\n";
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: '#666',
                        width: 0,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: ['#999', '#999']
                    }
                },
                // minInterval: 1,
                // splitNumber: 4,


                axisLabel: {
                    inside: false,
                    margin: 5,
                },
                axisLine: {
                    lineStyle: {
                        color: '#cdcdcd',
                        width: 1,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: ['transparent']
                    }
                },
                // minInterval: 1,
                splitNumber: 4,
            }],
            series: [{
                name: '',
                type: 'line',
                data: y,
                symbol: 'none',
                smooth: true,
                itemStyle: {
                    normal: {
                        color: '#e6262e',
                    }
                },
                // markLine : {
                //     symbol : ['none','none'],
                //     data:[
                //         {type:'average',name:'平均值',yAxis:y[y.length - 1],value:y[y.length - 1]}
                //     ],
                //     itemStyle : {
                //             normal: {
                //                 lineStyle: {color:'orange'},
                //                 barBorderColor:'orange',
                //                 label:{
                //                     position:'middle',
                //                     formatter:function(params){
                //                         return "\t" + params.value;
                //                     },
                //                     textStyle:{color:'orange'}
                //                 }
                //             }
                //         }
                // }
            }]
        };
        // chart.setOption($.extend(true, option, JSON.parse($("#lineOption").html())));
        chart.setOption(option, true);

    }

    // K线
    var getKLine = function(unit) {
        setData(unit);
        // 计算均线
        // 计算均线
        var calculateMA = function(dayCount, data) {
            var result = [];
            for (var i = 0, len = data.length; i < len; i++) {
                if (i < Number(dayCount)) {
                    result.push('-');
                    continue;
                }
                var sum = 0;
                for (var j = 0; j < Number(dayCount); j++) {
                   sum += Number(data[i - j][1]);
                }
                result.push((Number(sum) / Number(dayCount)).toFixed(2));
            }
            return result;
        };
        var length = data[pid][unit].x.length;
        if (length > 30) {
            data[pid][unit].x = data[pid][unit].x.slice(length - 30);
            data[pid][unit].y = data[pid][unit].y.slice(length - 30);
        }
        var option = {
            backgroundColor: 'transparent',
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    if (unit == 1440) {
                        return new Date(Number(params[0].name) * 1000).format('MM/dd') + '<br/>' +
                            "开盘价：" + params[0].value[0] + "<br>" +
                            "收盘价：" + params[0].value[1] + "<br>" +
                            "最低价：" + params[0].value[2] + "<br>" +
                            "最高价：" + params[0].value[3] + "<br>" +
                            "MA5：" + params[1].value + "<br>" + 
                            "MA10：" + params[2].value + "<br>" + 
                            "MA20：" + params[3].value + "<br>";
                    } else {
                        return new Date(Number(params[0].name) * 1000).format('hh:mm') + '<br/>' +
                            "开盘价：" + params[0].value[0] + "<br>" +
                            "收盘价：" + params[0].value[1] + "<br>" +
                            "最低价：" + params[0].value[2] + "<br>" +
                            "最高价：" + params[0].value[3] + "<br>" +
                            "MA5：" + params[1].value + "<br>" + 
                            "MA10：" + params[2].value + "<br>" + 
                            "MA20：" + params[3].value + "<br>";
                    }
                },
            },
            grid: {
                show: false,
                left: '1.5%',
                right: '1%',
                bottom: '0%',
                containLabel: true,
                borderWidth: 0,
                borderColor: 'white',
                y: 20,
                x2: 5,
                x: 45,
                y2: 40,
                borderWidth: 0
            },
            animation: true,
            xAxis: {
                type: 'category',
                data: data[pid][unit].x,
                axisLabel: {
                    formatter: function(value, index) {
                        if (index == 0) {
                            prefix = '      ';
                        } else {
                            prefix = '';
                        }
                        if (unit == 1440) {
                            return prefix + new Date(Number(value) * 1000).format('MM/dd');
                        } else {
                            return prefix + new Date(Number(value) * 1000).format('hh:mm');
                        }
                    },
                    interval: 'auto',
                },
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
            },
            yAxis: [{
                type: 'value',
                scale: true,
                axisLabel: {
                    inside: false,
                    margin: 5,
                },
                axisLine: {
                    lineStyle: {
                        color: '#cdcdcd',
                        width: 1,
                    },
                },
                splitLine: {
                    lineStyle: {
                        color: ['transparent']
                    }
                },
                // minInterval: 1,
                splitNumber: 4,
            }],
            series: [{
                type: 'candlestick',
                data: data[pid][unit].y,
                itemStyle: {
                    normal: {
                        color: 'rgb(255, 48, 48)',
                        color0: 'rgb(10, 185, 43)',
                        borderColor: 'rgb(255, 48, 48)',
                        borderColor0: 'rgb(10, 185, 43)'
                    }
                },
                markLine: {
                    symbol: ['arrow', 'none'],
                    symbolSize: [4, 2],
                    data: [{
                        yAxis: data[pid][unit].y[data[pid][unit].y.length - 1][1],
                        value: data[pid][unit].y[data[pid][unit].y.length - 1][1]
                    }],
                    itemStyle: {
                        normal: {
                            lineStyle: {
                                color: 'orange'
                            },
                            label: {
                                position: 'start',
                                textStyle: {
                                    color: 'orange'
                                },
                                formatter:function (params) {
                                    return  "                                                                   " +params.value ;
                                }
                            }
                        }
                    }
                }
            },{
                name: 'MA5',
                type: 'line',
                symbol:'none',
                data: calculateMA(5, data[pid][unit].y),
                smooth: true,
                showSymbol: true,
                lineStyle: {
                    normal: {
                        width: 1,
                        color: 'red'
                    },
                }
            },{
                name: 'MA10',
                type: 'line',
                symbol:'none',
                data: calculateMA(10, data[pid][unit].y),
                smooth: true,
                showSymbol: true,
                lineStyle: {
                    normal: {
                        width: 1,
                        color: 'yellow'
                    }
                }
            },
            {
                name: 'MA20',
                type: 'line',
                symbol:'none',
                data: calculateMA(20, data[pid][unit].y),
                smooth: true,
                showSymbol: true,
                lineStyle: {
                    normal: {
                        width: 1,
                        color: 'purple'
                    }
                }
            },]
        };
        // chart.setOption($.extend(true, option, JSON.parse($("#kOption").html())));
        chart.setOption(option, true);

    }
        // 更新所有数据价格
    var updatePrice = function(data, price, unit) {
        var time = Date.parse(new Date()) / 1000,
            diff = 60 * unit,
            count = data.x.length,
            lastTime = parseInt(data.x[count - 1]);
        if (time - lastTime > diff) {
            data.x.push(lastTime + diff);
            var row = [price, price, price, price];
            data.y.push(row);
        } else {
            data.y[count - 1][1] = price;
            data.y[count - 1][2] = data.y[count - 1][2] > price ? price : data.y[count - 1][2];
            data.y[count - 1][3] = data.y[count - 1][3] < price ? price : data.y[count - 1][3];
        }
    };
    // console.log($('.productPrice25').data('name'));
    // 实时获取价格
    var getPrice = function() {
        $.get('/price.json?' + Math.random(), function(msg, status, xhr) {
            var t=xhr.getResponseHeader('Date');
            var h = new Date(t).getHours();
            h = h < 10 ? "0" + h : h;
            var m = new Date(t).getMinutes();
            m = m < 10 ? "0" + m : m;
            var s = new Date(t).getSeconds();
            s = s < 10 ? "0" + s : s;
            t = h + ":" + m + ":" + s;
            $(".now").html(t);
            var isTradeList = {};
            for (var name in msg) {
                var $this = $("#" + name);
                    isTrade = $this.data('istrade'),
                    point = $this.data('point');
                    isTradeList[productMap[name]] = isTrade,
                    $productPrice = $("#" + name),
                    beforePrice = Number($this.html());
                    // var product =  $('.productPrice25').data('name');
                    // console.log(msg[name]);
                if (isTrade == 1) {
                    if (Number(msg[name]) > beforePrice) {
                        $this.removeClass().addClass('up-color');
                        $this.next().removeClass().addClass('up-color').html('↑');
                    } else {
                        $this.removeClass().addClass('down-color');
                        $this.next().removeClass().addClass('down-color').html('↓');
                    }
                    $this.html(Number(msg[name]));
                } else {
                    $this.removeClass().addClass('color-lightgray').html("休市"); 
                    $this.next().removeClass().html("");
                }

                var val = $("#productList a.active span").html();
                $(".now_price").html( val );
            }
            for (var name in msg) {
                if (data[productMap[name]]) {
                    for (var key in data[productMap[name]]) {
                        updatePrice(data[productMap[name]][key], msg[name], key);
                        showChart();
                    }
                }
            }

            setTimeout(function() {
                if (isTrade) {
                    getPrice();
                }
            }, 2000);
        }, 'json');
    };;
    !(function() {
        $("#productList>a").each(function() {
            productMap[$(this).data('name')] = $(this).data('id');
        });
        rawData[pid] = {};
        data[pid] = {};
        getRawData(function() {
            getKLine(1);
            getPrice();
        });
    })();
});